<?php
/**
 * 分销佣金记录模型
 */

namespace app\model;

use think\Model;

class DistributionCommissionModel extends Model
{
    // 设置表名
    protected $name = 'sh_distribution_commission';
    
    // 设置主键
    protected $pk = 'id';
    
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    
    /**
     * 获取佣金记录列表
     */
    public static function getCommissionRecords($filter = [], $page = 1, $limit = 15)
    {
        $query = self::alias('dc')
            ->join('customer c', 'dc.customer_id = c.id')
            ->join('customer cc', 'dc.from_customer_id = cc.id', 'left')
            ->field('dc.*, c.name as customer_name, cc.name as from_customer_name');
            
        // 根据分销员ID筛选
        if (!empty($filter['customer_id'])) {
            $query->where('dc.customer_id', $filter['customer_id']);
        }
        
        // 根据来源用户姓名筛选
        if (!empty($filter['customer_name'])) {
            $query->where('c.name', 'like', '%' . $filter['customer_name'] . '%');
        }
        
        // 根据状态筛选
        if (!empty($filter['status'])) {
            $query->where('dc.status', $filter['status']);
        }
        
        // 根据时间范围筛选
        if (!empty($filter['start_time'])) {
            $query->where('dc.create_time', '>=', $filter['start_time']);
        }
        
        if (!empty($filter['end_time'])) {
            $query->where('dc.create_time', '<=', $filter['end_time']);
        }
        
        $list = $query->page($page, $limit)->order('dc.create_time', 'desc')->select();
        $total = $query->count();
        
        return [
            'list' => $list,
            'total' => $total
        ];
    }
    
    /**
     * 添加佣金记录
     */
    public static function addCommissionRecord($data)
    {
        return self::create($data);
    }
    
    /**
     * 更新佣金记录
     */
    public static function updateCommissionRecord($id, $data)
    {
        return self::where(['id' => $id])->update($data);
    }
    
    /**
     * 删除佣金记录
     */
    public static function deleteCommissionRecord($id)
    {
        return self::where(['id' => $id])->delete();
    }
}